package com.codeduck.poi.controller.excel;

import com.codeduck.poi.util.AttachmentExportUtil;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;

/**
 * 设置单元格样式
 *
 * @author: <a href="mailto:codeduck@163.com">Codeduck</a>
 * @date: 2023/2/4
 */
@RestController
public class FormatCellStyleController {
    @GetMapping("format/cell/style")
    public void writeToFormulaCell(HttpServletResponse response) {
        Workbook workbook = new HSSFWorkbook();
        Sheet sheet = workbook.createSheet("sheet1");
        Row row = sheet.createRow(0);

        // 设置背景颜色
        CellStyle cellStyle = workbook.createCellStyle();
        cellStyle.setFillForegroundColor(IndexedColors.RED.index);
        cellStyle.setFillPattern(FillPatternType.BIG_SPOTS);

        Cell cell = row.createCell(0);
        cell.setCellStyle(cellStyle);
        cell.setCellValue("Hello");

        // 设置背景颜色
        cellStyle = workbook.createCellStyle();
        cellStyle.setFillForegroundColor(IndexedColors.YELLOW.index);
        cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);


        cell = row.createCell(1);
        cell.setCellStyle(cellStyle);
        cell.setCellValue("World");

        Row secodRow = sheet.createRow(1);
        cell = secodRow.createCell(0);
        cell.setCellValue("");
        cell = secodRow.createCell(1);
        cell.setCellValue("");
        // 居中
        cellStyle = workbook.createCellStyle();
        cellStyle.setAlignment(HorizontalAlignment.CENTER);

        // 合并单元格
        sheet.addMergedRegion(new CellRangeAddress(1, 1, 0,1));
        sheet.getRow(1).getCell(0).setCellStyle(cellStyle);
        sheet.getRow(1).getCell(0).setCellValue("你好！世界！");

        AttachmentExportUtil.export(workbook, "formatCellStyle", response);
    }
}
